package net.ming616.nlp.rite.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import net.ming616.nlp.rite.model.RiteModel;
import net.ming616.nlp.rite.service.NTCIRManager;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

@Service("ntcirManager")
public class NTCIRManagerImpl implements NTCIRManager {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(NTCIRManagerImpl.class);

	String riteDataFile = "/sample_rite_sc.xml";

	List<RiteModel> riteList;

	@PostConstruct
	List<RiteModel> load() {
		if (this.riteList == null) {
			this.riteList = new ArrayList<RiteModel>();
			Document doc = null;
			try {
				InputStream riteInputStream = this.getClass()
						.getResourceAsStream(this.riteDataFile);
				doc = Jsoup.parse(riteInputStream, "UTF-8", "");
			} catch (IOException e) {
				logger.error(e.getMessage());
			}
			Elements paris = doc.select("pair");
			for (Element pair : paris) {
				RiteModel ritePair = new RiteModel();
				String id = pair.attr("id");
				String label = pair.attr("label");
				String text = pair.select("t1").text();
				String hypo = pair.select("t2").text();
				ritePair.setId(id);
				ritePair.setLabel(label);
				ritePair.setText(text);
				ritePair.setHypo(hypo);
				this.riteList.add(ritePair);

			}
		}
		return this.riteList;
	}

	public List<RiteModel> getAllRitePairs() {
		if (null == this.riteList) {
			this.load();
		}
		return this.riteList;
	}

}
